#include "lettershell/shell.h"
#include "qlcommon.h"
#include "modem/qlmodem/task_modem.h"
#include "global.h"
#include <stdio.h>

static int modem_recv(const void *buf, size_t cnt, void *ptr)
{
    char* p_buf = NULL;

    if (cnt <= 0) {
        return -EBUSY;
    }

    p_buf = qlmalloc(cnt+1);
    if (p_buf == NULL) {
        return -ENOMEM;
    }
    memset(p_buf, '\0', cnt+1);

    taskENTER_CRITICAL();
    memcpy(p_buf,buf,cnt);
    taskEXIT_CRITICAL();

    p_buf[cnt] = '\0';

    printf("%s\r\n",p_buf);

    if (strstr(p_buf,"OK") == NULL &&
        strstr(p_buf,"ERROR") == NULL) {
        qlfree(p_buf);
        return -EBUSY;
    }

    qlfree(p_buf);
    return 0;
}

int32_t shell_modem_trans_cmd(int32_t argc, char *argv[])
{
    char* buf = NULL;
    int cnt = 0;
    
    if (2 > argc) {
        printf("argc is incorrect, %d\r\n", argc);
        return -EINVAL;
    }

    cnt = strlen(argv[1]);  

    buf = qlmalloc(cnt+2);

    if (buf == NULL) {
        printf("out of memory\r\n");
        return -ENOMEM;
    }

    memset(buf, '\0', cnt+2);

    snprintf(buf, cnt + 2, "%s\r", argv[1]);

    qltask_modem_direct_atcmd(buf, modem_recv, NULL, 5);

    qlfree(buf);

    return 0;
}
 
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN) | SHELL_CMD_DISABLE_RETURN,
                 MDMTRS,
                 shell_modem_trans_cmd,
                 modem transparent transmission cmd);

